package com.northpool.operator.common.database;

import com.northpool.commons.bits.HexUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;


public class PasswordCrypo {

    static final String DESedeKey = "1ja01jqz2112#2@$@%%#^*@$!241edd@1sdcaqxjqxjussd2";
    static final Cipher encodeCipher;
    static final Cipher decodeCipher;

    static {
        DESedeKeySpec desKeySpec;

        try {
            desKeySpec = new DESedeKeySpec(DESedeKey.getBytes());
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
            SecretKey convertSecretKey = factory.generateSecret(desKeySpec);
            // 加密
            encodeCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            decodeCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            encodeCipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            decodeCipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    public synchronized static String encode(String password) {
        byte[] result;
        try {
            result = encodeCipher.doFinal(password.getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return HexUtils.bytesToHexString(result);
    }

    public synchronized static String decode(String passwordEncode) {
        return decode(passwordEncode, Charset.defaultCharset());
    }

    public synchronized static String decode(String passwordEncode, Charset charset) {
        byte[] result;
        try {
            result = decodeCipher.doFinal(HexUtils.hexStringToByteArray(passwordEncode));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return new String(result, charset);
    }


    public static void main(String[] aaa) {
        System.out.print(encode("zhangzhaoyang"));

    }


}
